package cz.byteworks.exportino;

import java.lang.reflect.InvocationTargetException;
import java.util.Collection;

import org.apache.commons.beanutils.PropertyUtils;

public class FilterTool {

    public static boolean isEligible(IRecord record, IRecordFilter filter) {
        if (filter == null || filter.getPropertyName() == null || record == null) {
            return false;
        }
        try {
            Object value = PropertyUtils.getProperty(record, filter.getPropertyName());
            if (value == null) {
                if (filter.getValueToCompare() == null && filter.getFilterType().equals(IRecordFilter.FilterType.EQUAL)) {
                    return true;
                }
                return false;
            }
            else {
            	switch (filter.getFilterType()) {
				case EQUAL:
					return value.equals(filter.getValueToCompare());
				case CONTAIN:
					if (value instanceof Collection<?>) {
						return ((Collection<?>)value).contains(filter.getValueToCompare());
					}
					else {
						if (filter.getValueToCompare() == null) {
							return true;
						}
						return value.toString().indexOf(filter.getValueToCompare().toString()) >= 0;
					}
				case NOT_EQUAL:
					return !value.equals(filter.getValueToCompare());
				default:
					return false;
				}
            }       
        } catch (NoSuchMethodException e) {
            return false;
        } catch (IllegalAccessException e) {
            return false;
        } catch (InvocationTargetException e) {
            return false;
        }
    }

    public static boolean isEligible(IRecord record, Collection<IRecordFilter> filters) {
        for (IRecordFilter oneFilter : filters) {
            if (!isEligible(record, oneFilter)) {
                return false;
            }
        }
        return true;
    }

}
